
function calcFeatureCollection(data) {

    var temp = calcFeature(data.features[0]);

    var minX = temp.minX;
    var maxX = temp.maxX;
    var minY = temp.minY;
    var maxY = temp.maxY;
    var centers = [[
        (temp.maxX + temp.minX) * 0.5,
        (temp.maxY + temp.minY) * 0.5
    ]];

    for (var i = 1; i < data.features.length; i++) {
        var temp = calcFeature(data.features[i]);

        if (temp.minX < minX) minX = temp.minX;
        if (temp.maxX > maxX) maxX = temp.maxX;
        if (temp.minY < minY) minY = temp.minY;
        if (temp.maxY > maxY) maxY = temp.maxY;

        centers.push([
            (temp.maxX + temp.minX) * 0.5,
            (temp.maxY + temp.minY) * 0.5
        ]);
    }

    return {
        minX: minX,
        maxX: maxX,
        minY: minY,
        maxY: maxY,
        centers: centers
    };

}

function calcFeature(data) {

    if (data.geometry.type == 'Polygon') {
        return calcPolygon(data.geometry.coordinates);
    } else {
        return calcMultiPolygon(data.geometry.coordinates);
    }

}

function calcMultiPolygon(data) {

    var minX = data[0][0][0][0];
    var maxX = data[0][0][0][0];
    var minY = data[0][0][0][1];
    var maxY = data[0][0][0][1];

    for (var i = 0; i < data.length; i++) {
        var temp = calcPolygon(data[i]);

        if (temp.minX < minX) minX = temp.minX;
        if (temp.maxX > maxX) maxX = temp.maxX;
        if (temp.minY < minY) minY = temp.minY;
        if (temp.maxY > maxY) maxY = temp.maxY;

    }

    return {
        minX: minX,
        maxX: maxX,
        minY: minY,
        maxY: maxY
    };

}

function calcPolygon(data) {

    var minX = data[0][0][0];
    var maxX = data[0][0][0];
    var minY = data[0][0][1];
    var maxY = data[0][0][1];

    for (var i = 0; i < data.length; i++) {
        for (var j = 0; j < data[i].length; j++) {

            if (minX > data[i][j][0]) minX = data[i][j][0];
            else if (maxX < data[i][j][0]) maxX = data[i][j][0];

            if (minY > data[i][j][1]) minY = data[i][j][1];
            else if (maxY < data[i][j][1]) maxY = data[i][j][1];

        }
    }

    return {
        minX: minX,
        maxX: maxX,
        minY: minY,
        maxY: maxY
    };

}

export default function (data) {

    var temp;

    if (data.type == 'FeatureCollection') {
        temp = calcFeatureCollection(data);
    } else if (data.type == 'Feature') {
        temp = calcFeature(data);
    } else {
        throw new Error('Type error!' + JSON.stringify({ function: "getCenter", type: data.type }));
    }

    return [
        (temp.maxX + temp.minX) * 0.5,
        (temp.maxY + temp.minY) * 0.5,
        temp.maxX - temp.minX,
        temp.maxY - temp.minY,
        temp.centers
    ];

};
